package com.compmov.socialnetwork;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.compmov.datamodel.Persona;
import com.compmov.webservice.PersonaWSClient;
import com.compmov.webservice.WSClientException;

public class DatosPersona extends Activity {
	private TextView usuario;
	private TextView nombre;
	private TextView correo;
	private TextView sexo;
	private TextView fechaNac;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.datos_persona);

		this.usuario = (TextView) findViewById(R.id.nombreUser);
		this.nombre = (TextView) findViewById(R.id.nombre_per);
		this.correo = (TextView) findViewById(R.id.correo_per);
		this.sexo = (TextView) findViewById(R.id.sexo_per);
		this.fechaNac = (TextView) findViewById(R.id.fecha_per);

		Persona per = com.compmov.libraries.Utils.getPersona();
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			int idPer=bundle.getInt("idPer");
			Persona persona=new Persona();
			persona.setId(idPer);
			PersonaWSClient personaWS = new PersonaWSClient("persona");
			try {
				per= personaWS.getPersona(persona);	
			} catch (WSClientException e) {
				Toast.makeText(getBaseContext(),"Error en el servidor. Intente de nuevo",
						Toast.LENGTH_SHORT).show();
			}
		}
		
		usuario.setText(per.getNombreUsuario());
		nombre.setText(per.getNombrePersona() + " " + per.getApellidoPaterno()
				+ " " + per.getApellidoMaterno());
		correo.setText(per.getCorreo());
		fechaNac.setText(per.getFechaNacimiento());
		sexo.setText(per.getSexoStr());
		
		ImageView imgView =(ImageView)findViewById(R.id.foto_per);
		Drawable image = ImageOperations(this,per.getFotografia(),"image.jpg");
		imgView = (ImageView)findViewById(R.id.foto_per);
		imgView.setImageDrawable(image);

	}

	private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
		try {
			InputStream is = (InputStream) this.fetch(url);
			Drawable d = Drawable.createFromStream(is, "src");
			return d;
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public Object fetch(String address) throws MalformedURLException,IOException {
		URL url = new URL(address);
		Object content = url.getContent();
		return content;
	}

}
